<template>
  <div class="p-2">
    <transition>
      <div class="search" v-show="showSearch">
        <el-form
          :model="queryParams"
          ref="queryFormRef"
          :inline="true"
          label-width="68px"
        >
          <el-form-item label="角色名称" prop="name">
            <el-input
              v-model="queryParams.name"
              placeholder="请输入角色名"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <!-- <el-form-item label="权限字符" prop="name">
            <el-input
              v-model="queryParams.key"
              placeholder="请输入权限字符"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item> -->
          <el-form-item label="状态" prop="email">
            <el-select
              v-model="queryParams.status"
              clearable
              placeholder="请选择"
            >
              <el-option
                v-for="item in statusArr"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="注册时间" prop="age">
            <el-date-picker
              v-model="queryParams.timeRange"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              @change="handleDateRangeChange"
            />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">
              搜索
            </el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <!-- 按钮区 -->
    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb-1">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="Plus"
              @click="handleAdd"
              v-hasPermi="['system:role:add']"
            >
              新增
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="Edit"
              :disabled="single"
              @click="handleEdit()"
              v-hasPermi="['system:role:edit']"
            >
              修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="Delete"
              :disabled="multiple"
              @click="handleDelete()"
              v-hasPermi="['system:role:remove']"
            >
              删除
            </el-button>
          </el-col>
          <!-- <el-col :span="1.5">
            <el-button
              type="info"
              plain
              icon="Delete"
              :disabled="multiple"
              v-hasPermi="['system:user:import']"
              >导入</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="info"
              plain
              icon="Delete"
              :disabled="multiple"
              v-hasPermi="['system:user:export']"
              >导出</el-button
            >
          </el-col> -->
          <right-toolbar
            v-model:showSearch="showSearch"
            @queryTable="getRoleList"
          ></right-toolbar>
        </el-row>
      </template>

      <!-- 列表区 -->
      <el-table
        v-loading="loading"
        :data="roleList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="30" align="center" />
        <!-- <el-table-column label="角色ID" align="center" prop="id" v-if="true" /> -->

        <el-table-column label="角色名称" align="center" prop="name" />
        <!-- <el-table-column label="权限字符" align="center" prop="key" /> -->

        <el-table-column label="状态" prop="status">
          <template #default="{ row }">
            <el-tag :type="statusType(row.status)">{{ row.status }}</el-tag>
          </template>
        </el-table-column>

        <el-table-column label="成员人数" align="center" prop="totalPeople" />
        <el-table-column label="备注" align="center" prop="remark" />
        <el-table-column label="创建时间" align="center" prop="createTime" />

        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template #default="scope">
            <el-tooltip content="管理成员" placement="top" :enterable="false">
              <el-button
                link
                type="primary"
                v-hasPermi="['system:role:list']"
                @click="handleMemberDetail(scope.row)"
              >
                <icon-ic-outline-group />
              </el-button>
            </el-tooltip>
            <el-tooltip content="编辑" placement="top" :enterable="false">
              <el-button
                link
                type="primary"
                icon="Edit"
                @click="handleEdit(scope.row)"
                v-hasPermi="['system:role:edit']"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top" :enterable="false">
              <el-button
                link
                type="primary"
                icon="Delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['system:user:remove']"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getRoleList"
      />
    </el-card>

    <!-- 角色详情弹出框 -->
    <el-dialog
      v-model="newDialogStatus.isShow"
      :title="newDialogStatus.title"
      width="35%"
      center
      append-to-body
      :show-close="false"
      :close-on-click-modal="false"
      @close="handleCloseNewDialog"
    >
      <el-form
        :model="newDialogData"
        ref="diologFormRef"
        :inline="true"
        :rules="rules"
        label-width="78px"
        class="dialogForm"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input
            v-model="newDialogData.name"
            placeholder="请输入角色名"
            clearable
            @keyup.enter="handleQuery"
            style="width: 220px"
          />
        </el-form-item>
        <!-- <el-form-item label="权限字符" prop="key">
          <el-input
            v-model="currentDialogData.key"
            placeholder="请输入用户名"
            clearable
            @keyup.enter="handleQuery"
            style="width: 220px"
          />
        </el-form-item> -->
        <!-- <el-form-item label="角色顺序" prop="orderNum">
          <el-input-number
            v-model="currentDialogData.orderNum"
            :min="1"
            :max="20"
          />
        </el-form-item> -->

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="newDialogData.status">
            <el-radio label="0">正常</el-radio>
            <el-radio label="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="审核角色" prop="identity">
          <el-select
            v-model="newDialogData.identityIdList"
            clearable
            multiple
            placeholder="请选择"
          >
            <el-option
              v-for="item in identityArr"
              :key="(item as any).id"
              :label="(item as any).name"
              :value="(item as any).id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input
            style="width: 20vw"
            v-model="newDialogData.remark"
            placeholder="请输入"
            clearable
            type="textarea"
            @keyup.enter="handleQuery"
            :rows="6"
            :col="10"
          />
        </el-form-item>

        <el-form-item class="innerDialogFooter">
          <el-button
            type="primary"
            icon="Search"
            @click="handleNewDialogSubmit"
          >
            提交
          </el-button>
          <el-button icon="Refresh" @click="newDialogStatus.isShow = false"
            >关闭</el-button
          >
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 角色成员弹出框 -->
    <el-dialog
      v-model="membersDialogStatus.isShow"
      :title="membersDialogStatus.title"
      width="60%"
      center
      append-to-body
      :close-on-click-modal="false"
      @close="handleCloseMembersDialog"
    >
      <template #header="{ titleId, titleClass }">
        <div :id="titleId" :class="titleClass" class="mb-4">
          {{ membersDialogStatus.title }}
        </div>
        <el-row
          :gutter="10"
          class="mb-1 flex justify-between"
          v-if="membersDialogStatus.isAddMembers"
        >
          <div>
            <el-button
              type="info"
              plain
              icon="Back"
              @click="handleBack"
              v-hasPermi="['system:user:add']"
            >
              返回
            </el-button>

            <el-button
              type="primary"
              plain
              icon="Plus"
              @click="handleAddUserToRole()"
              :disabled="membersDialogStatus.multiple"
              v-hasPermi="['system:userRole:add']"
            >
              添加
            </el-button>
          </div>
          <div>
            <el-input
              v-model="innerUserParams.userName"
              placeholder="请输入用户名"
              class="w-200px!"
            />
            <el-button
              type="primary"
              icon="Search"
              @click="handleSearch"
              v-hasPermi="['system:user:add']"
              class="ml-12px"
            >
              搜索
            </el-button>
          </div>
        </el-row>
        <el-row :gutter="10" class="mb-1" v-else>
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="Plus"
              @click="handleAddUserToRoleDialog"
              v-hasPermi="['system:userRole:add']"
            >
              添加成员
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="Delete"
              :disabled="membersDialogStatus.multiple"
              @click="handleRemoveUserFromRole()"
              v-hasPermi="['system:userRole:remove']"
            >
              移出
            </el-button>
          </el-col>
        </el-row>
      </template>

      <div v-if="membersDialogStatus.isAddMembers">
        <el-table
          v-loading="loading"
          :data="innerSearchUserList"
          @selection-change="handleDialogSelectionChange"
        >
          <el-table-column type="selection" width="30" align="center" />
          <el-table-column label="用户名称" align="center" prop="userName" />
          <el-table-column
            label="机构"
            align="center"
            prop="organizationName"
          />
          <el-table-column label="岗位" align="center" prop="job" />

          <!-- <el-table-column label="状态" prop="status">
          <template #default="{ row }">
            <el-tag :type="statusType(row.status)">{{ row.status }}</el-tag>
          </template>
        </el-table-column> -->

          <el-table-column label="手机号" align="center" prop="phoneNumber" />

          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
          >
            <template #default="scope">
              <el-button
                v-if="!scope.row.belong"
                link
                type="primary"
                v-hasPermi="['system:userRole:add']"
                @click="handleAddUserToRole(scope.row)"
              >
                添加
              </el-button>

              <el-button link v-else>已添加</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-else>
        <el-table
          v-loading="loading"
          :data="innerMemberUserList"
          @selection-change="handleDialogSelectionChange"
        >
          <el-table-column type="selection" width="30" align="center" />
          <el-table-column label="用户名称" align="center" prop="userName" />
          <el-table-column
            label="机构"
            align="center"
            prop="organizationName"
          />
          <el-table-column label="岗位" align="center" prop="job" />

          <!-- <el-table-column label="状态" prop="status">
          <template #default="{ row }">
            <el-tag :type="statusType(row.status)">{{ row.status }}</el-tag>
          </template>
        </el-table-column> -->

          <el-table-column label="手机号" align="center" prop="phoneNumber" />

          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
          >
            <template #default="scope">
              <el-button
                link
                type="primary"
                v-hasPermi="['system:userRole:remove']"
                @click="handleRemoveUserFromRole(scope.row)"
              >
                移出
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <template #footer>
        <pagination
          v-if="membersDialogStatus.isAddMembers"
          v-show="innerTotal > 0"
          :total="innerTotal"
          :page-sizes="[5, 10, 15, 20]"
          v-model:page="innerParams.pageNum"
          v-model:limit="innerParams.pageSize"
          @pagination="getUserNotInRoleList"
        />
        <pagination
          v-else
          v-show="innerTotal > 0"
          :total="innerTotal"
          :page-sizes="[5, 10, 15, 20]"
          v-model:page="innerParams.pageNum"
          v-model:limit="innerParams.pageSize"
          @pagination="getMemberList"
        />
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {
  getRoleList as getRoleListApi,
  addRole as addRoleApi,
  getRoleMemberList as getRoleMemberListApi,
  getRoleDetail as getRoleDetailApi,
  updateRole as updateRoleApi,
  deleteRole as deleteRoleApi,
  removeUsersFromRole as removeUsersFromRoleApi,
  getUserListNotInRole as getUserListNotInRoleApi,
  addUsersToRole as addUsersToRoleApi,
  getIdentityArr as getIdentityArrApi,
} from "@/service/api/system/role";
import { checkUser } from "@/service/api/system/user/types.ts";
import {
  CheckUser,
  SysIdentityVo,
  SysUserVo,
} from "@/service/api/system/role/types";
import { ElButton, ElForm } from "element-plus";
import { to } from "await-to-js";
import { convertTimeRange } from "@/utils/request.ts";
import RightToolbar from "@/components/RightToolbar/index.vue";
import Pagination from "@/components/Pagination/index.vue";
import { SysRoleVo } from "@/service/api/system/role/types.ts";
import { BasePageResponse, BaseResponse } from "@/service/api/type.ts";

// 列表数据
const roleList = ref<SysRoleVo[]>([]);

const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const innerTotal = ref(0);
const queryFormRef = ref(ElForm);

// 初始新建对话框状态
const initDialogStatus = {
  isShow: false,
  title: "",
};

// 初始成员管理对话框状态
const initMembersDialogStatus = {
  isShow: false,
  title: "",
  /**
   * 是否处于添加用户状态
   */
  isAddMembers: false,
  single: true,
  multiple: true,
  ids: <string[]>[],
};

// 状态
const statusArr = reactive([
  {
    value: "0",
    label: "正常",
  },
  {
    value: "1",
    label: "停用",
  },
]);
// 初始角色详情dialogData数据
const initDialogData: SysRoleVo = {
  name: "",
  key: "",
  orderNum: 0,
  status: "0",
  id: "",
  remark: "",
  permissionIds: <string[]>[],
  identityIdList: <string[]>[],
};
// 初始query参数
const initQueryParams = {
  pageNum: 1,
  pageSize: 10,
  status: "",
  name: "",
  timeRange: [null, null],
  key: "",
  remark: "",
  orderByColumn: "createTime",
  orderType: "desc",
  params: {
    beginTime: <string | null>null,
    endTime: <string | null>null,
  },
};
// 初始inner参数
const initInnerParams = {
  userId: "",
  roleId: "",
  pageNum: 1,
  pageSize: 5,
};
// 初始移出参数
const initInnerRemoveParams = {
  userIds: <string[]>[],
  roleId: "",
};
// 搜索框数据
const initInnerUserParams = {
  pageNum: 1,
  pageSize: 5,
  roleId: "",
  userName: "",
};
const initAddUsersBO = {
  userIds: [],
  roleId: "",
};
const identityArr = ref<SysIdentityVo[]>([]);
// 搜索框数据
const data = reactive({
  queryParams: { ...initQueryParams },
  // 单个移出
  innerParams: {
    ...initInnerParams,
  },
  // 批量移出
  innerRemoveParams: {
    ...initInnerRemoveParams,
  },
  // 单个添加
  innerUserParams: {
    ...initInnerUserParams,
  },
  // 批量添加
  addUsersBO: { ...initAddUsersBO },
  rules: {
    name: [{ required: true, message: "角色名不能为空", trigger: "blur" }],
    key: [{ required: true, message: "角色key不能为空", trigger: "blur" }],
  },
  newDialogStatus: { ...initDialogStatus },
  membersDialogStatus: { ...initMembersDialogStatus },
  newDialogData: {
    ...initDialogData,
  },
  membersDialogData: {
    ...initDialogData,
  },
  // 已勾选的用户数据
  innerMemberUserList: <SysUserVo[]>[],
  // 搜索用户数据
  innerSearchUserList: <SysUserVo[]>[],
});
const {
  queryParams,
  newDialogData,
  membersDialogData,
  innerMemberUserList,
  innerSearchUserList,
  innerParams,
  newDialogStatus,
  membersDialogStatus,
  innerUserParams,
  innerRemoveParams,
  rules,
  addUsersBO,
} = toRefs(data);

/**
 * 搜索按钮操作
 */
const handleQuery = () => {
  // console.log(queryParams.value)
  queryParams.value.pageNum = 1;
  getRoleList();
};

/**
 * 重置按钮操作
 */
const resetQuery = () => {
  queryFormRef.value.resetFields();
  handleQuery();
};

/**
 * 将选择的开始结束日期转换为后端需要的形式
 * @param value
 */
const handleDateRangeChange = (value: [Date | null, Date | null]) => {
  console.log(value);
  queryParams.value.params = convertTimeRange(value);
};

/**
 * 获取角色列表
 * 不泄露异常
 */
const getRoleList = async () => {
  loading.value = true;
  const [err, response] = await to<BasePageResponse<SysRoleVo>, any>(
    getRoleListApi(queryParams.value),
  );
  if (!err) {
    roleList.value = response?.rows ?? [];
    roleList.value.map((item) => {
      if (item.status === "1") {
        item.status = "停用";
      } else if (item.status === "2") {
        item.status = "禁言";
      } else if (item.status === "3") {
        item.status = "未确认";
      } else {
        item.status = "正常";
      }
    });
    total.value = Number(response?.total ?? 0);
  }
  loading.value = false;
};

/**
 * 获取成员列表列表
 * 不泄露异常
 */
const getMemberList = async (): Promise<boolean> => {
  const [err, res] = await to<BasePageResponse<SysUserVo>, any>(
    getRoleMemberListApi(innerParams.value),
  );
  if (!err) {
    innerMemberUserList.value = res?.rows ?? [];
    innerTotal.value = Number(res?.total ?? 0);
    return true;
  }
  return false;
};
/**
 * 获取身份列表
 */
const getIdentityArr = async () => {
  const [err, res] = await to<BasePageResponse<SysIdentityVo>, any>(
    getIdentityArrApi(),
  );
  console.log(res);
  if (!err) {
    identityArr.value = res?.rows ?? [];
  }
};

/**
 * 设置状态类型
 * @param status
 */
const statusType = (status: string) => {
  switch (status) {
    case "正常":
      return "success";
    case "未确认":
      return "warning";
    case "禁言":
      return "danger";
    case "停用":
      return "info";
    default:
      return "";
  }
};

/**
 * 处理新建对话框中的提交按钮
 */
const handleNewDialogSubmit = () => {
  queryFormRef.value.validate(async (valid: boolean) => {
    // 通过验证
    if (valid) {
      // 有id为修改
      if (newDialogData.value.id) {
        console.log(1);

        const [err] = await to(updateRoleApi(newDialogData.value));
        if (!err) {
          newDialogStatus.value.isShow = false;
          ElMessage({
            message: "角色修改成功",
            type: "success",
          });
          getRoleList();
        }
      }
      // 无id为新增
      else {
        const [err] = await to(addRoleApi(newDialogData.value));
        if (!err) {
          newDialogStatus.value.isShow = false;
          ElMessage({
            message: "角色新增成功",
            type: "success",
          });
          getRoleList();
        }
      }
    } else {
      ElMessage({
        message: "验证失败",
        type: "error",
      });
    }
  });
};

/**
 * 处理关闭新建对话框
 */
const handleCloseNewDialog = async () => {
  newDialogStatus.value = Object.assign({}, initDialogStatus);
  newDialogData.value = Object.assign({}, initDialogData);
  loading.value = false;
  await getRoleList();
};

/**
 * 处理关闭成员管理对话框
 */
const handleCloseMembersDialog = async () => {
  membersDialogStatus.value = Object.assign({}, initMembersDialogStatus);
  membersDialogData.value = Object.assign({}, initDialogData);
  innerUserParams.value = Object.assign({}, initInnerUserParams);
  loading.value = false;
  await getRoleList();
};

/**
 * 主列表多选框选中数据
 */
const handleSelectionChange = (selection: CheckUser[]) => {
  ids.value = selection.map((item) => item.id);

  single.value = selection.length != 1;
  multiple.value = !selection.length;

  // const usefulSelection = selection.filter((item) => item.belong != true);
  // ids.value = usefulSelection.map((item) => item.id);
  //
  // single.value = usefulSelection.length != 1;
  // multiple.value = !usefulSelection.length;
  // console.log(ids.value);
  // innerRemoveParams.value.userIds = ids.value;
};

/**
 * 对话框多选框选中数据
 */
const handleDialogSelectionChange = (selection: CheckUser[]) => {
  const usefulSelection = selection.filter((item) => item.belong != true);
  membersDialogStatus.value.ids = usefulSelection.map((item) => item.id);

  membersDialogStatus.value.single = usefulSelection.length != 1;
  membersDialogStatus.value.multiple = !usefulSelection.length;

  innerRemoveParams.value.userIds = ids.value;
  console.log(membersDialogStatus.value.ids);
};

/**
 * 处理新增按钮
 */
const handleAdd = async () => {
  newDialogStatus.value.title = "添加角色";
  newDialogStatus.value.isShow = true;
};

/**
 * 处理成员管理按钮
 */
const handleMemberDetail = async (row: any) => {
  membersDialogStatus.value.title = "成员管理";
  // 获取roleId
  innerParams.value.roleId = row.id;
  // getAllMemberListBO.value.roleId = row.id
  innerRemoveParams.value.roleId = row.id;
  addUsersBO.value.roleId = row.id;
  innerUserParams.value.roleId = row.id;
  // await getAllMemberList()
  const response = await getMemberList();
  if (response) {
    membersDialogStatus.value.isShow = true;
  } else {
    ElMessage({
      message: "获取成员列表失败",
      type: "error",
    });
  }
};

/**
 * 处理编辑按钮操作
 */
const handleEdit = async (row?: checkUser) => {
  newDialogStatus.value.title = "编辑角色";
  loading.value = true;
  const id = row?.id || ids.value[0];
  const [err, res] = await to<BaseResponse<SysRoleVo>, any>(
    getRoleDetailApi(id),
  );
  if (!err) {
    console.log(res?.data);
    newDialogData.value = res?.data ?? initDialogData;
    newDialogStatus.value.isShow = true;
  }
  loading.value = false;
};

/**
 * 处理删除按钮操作
 */
const handleDelete = async (row?: checkUser) => {
  const _ids = row?.id || ids.value;
  console.log(_ids);
  const [err, confirm] = await to<string, string>(
    ElMessageBox.confirm("是否确定删除选中的角色？", "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }),
  );
  if (err === "cancel") {
    ElMessage({
      type: "info",
      message: "取消删除",
    });
  } else if (confirm === "confirm") {
    const [err] = await to(deleteRoleApi(_ids));
    if (!err) {
      ElMessage({
        type: "success",
        message: "删除成功",
      });
    }
    await getRoleList();
  }
};
// const getAllMemberListBO = ref({
//   roleId:'',
//   pageSize:50,
//   pageNum:1,
// })
// 获取所有已勾选的用户
// const getAllMemberList = async () => {
//   const [err,res] = await to(getRoleMemberListApi(getAllMemberListBO.value))
//   if(!err) {
//     console.log(res);
//   }
// }

/**
 * 获取所有不在角色中用户列表
 */
const getUserNotInRoleList = async () => {
  const [err, res] = await to<BasePageResponse<SysUserVo>, any>(
    getUserListNotInRoleApi(innerParams.value),
  );
  if (!err) {
    console.log(res?.rows);
    innerSearchUserList.value = res?.rows ?? [];
    // innerSearchUserList.value.map((item: any) => {
    //   const is = innerMemberUserList.value.find((subItem: any) => {
    //     return subItem.id === item.id
    //   })
    //   console.log(is);
    // })
    innerTotal.value = Number(res?.total ?? 0);
  }
};

/**
 * 处理添加用户到角色中按钮
 */
const handleAddUserToRoleDialog = async () => {
  membersDialogStatus.value.isAddMembers = true;
  getUserNotInRoleList();
};

/**
 * 处理从角色中移出用户按钮
 * @param row
 */
const handleRemoveUserFromRole = async (row?: any) => {
  // 询问是否删除
  const msg = row
    ? "是否确定从角色中移出该用户？"
    : "是否确定从角色中移出选中的用户？";
  const [err, confirm] = await to<string, string>(
    ElMessageBox.confirm(msg, "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }),
  );
  if (err === "cancel") {
    ElMessage({
      type: "info",
      message: "取消移除",
    });
  } else if (confirm === "confirm") {
    let roleId: string;
    let userIds: string[];
    // 单个移出
    if (row) {
      roleId = innerParams.value.roleId;
      console.log(row);
      userIds = [row.id];
    }
    // 批量移出
    else {
      roleId = innerRemoveParams.value.roleId;
      userIds = membersDialogStatus.value.ids;
    }

    const [err] = await to<BaseResponse<any>, any>(
      removeUsersFromRoleApi(roleId, userIds),
    );
    if (!err) {
      ElMessage({
        message: "移出成功",
        type: "success",
      });
      innerParams.value.userId = "";
      innerRemoveParams.value.userIds = [];
      // 移出之后刷新用户列表
      getMemberList();
    }
  }
};

/**
 * 处理返回按钮
 */
const handleBack = () => {
  membersDialogStatus.value.isAddMembers = false;
  membersDialogStatus.value.multiple = true;
  membersDialogStatus.value.single = true;
  innerUserParams.value.userName = "";
  getMemberList();
};

/**
 * 处理dialog的用户搜索按钮
 */
const handleSearch = async () => {
  const [err, res] = await to<BasePageResponse<SysUserVo>, any>(
    getUserListNotInRoleApi(innerUserParams.value),
  );
  if (!err) {
    innerSearchUserList.value = res?.rows ?? [];
    innerTotal.value = Number(res?.total ?? 0);
    console.log(innerSearchUserList.value);
  }
};

/**
 * 处理添加用户到角色
 * @param row
 */
const handleAddUserToRole = async (row?: any) => {
  // 询问是否确定添加
  const msg = row
    ? "是否确定添加该用户到角色？"
    : "是否确定添加选中的用户到角色？";
  const [err, confirm] = await to<string, string>(
    ElMessageBox.confirm(msg, "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }),
  );
  if (err === "cancel") {
    ElMessage({
      type: "info",
      message: "取消添加",
    });
  } else if (confirm === "confirm") {
    let roleId: string;
    let userIds: string[];

    // 单个添加
    if (row) {
      roleId = innerParams.value.roleId;
      userIds = [row.id];
    }
    // 批量添加成员
    else {
      roleId = addUsersBO.value.roleId;
      userIds = membersDialogStatus.value.ids;
    }
    const [err] = await to(addUsersToRoleApi(roleId, userIds));
    if (!err) {
      newDialogStatus.value = Object.assign({}, initDialogStatus);
      ElMessage({
        message: "添加成功",
        type: "success",
      });
      await getUserNotInRoleList();
    } else {
      newDialogStatus.value = Object.assign({}, initDialogStatus);
      addUsersBO.value = Object.assign({}, initAddUsersBO);
      await getUserNotInRoleList();
    }
    addUsersBO.value = Object.assign({}, initAddUsersBO);
  }
};

onMounted(async () => {
  await getRoleList();
  await getIdentityArr();
});
</script>

<style scoped lang="scss">
.el-date-pickerv {
  width: 900px;
}

.dialogForm {
  padding: 0 0 0 45px;

  // background-color: pink;
  .el-input {
    width: 219px;
  }
}

.dialogFooter {
  margin: 55px 0 0 220px;
}

.innerDialogFooter {
  margin: 55px 0 0 200px;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;

  .setting {
    margin-left: 30px;
  }
}

.innerFooter {
  margin: 20px 0 0 200px;
}
</style>
